﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Text;

namespace SharpSoft.Net
{
    public abstract class HttpServiceBase : IDisposable
    {
        HttpListener httpListener;
        public HttpServiceBase(int port)
        {
            //提供一个简单的、可通过编程方式控制的 HTTP 协议侦听器。此类不能被继承。
            httpListener = new HttpListener();
            //定义url及端口号，通常设置为配置文件
            httpListener.Prefixes.Add($"http://+:{port}/");

        }
        /// <summary>
        /// 开始监听
        /// </summary>
        public void Start()
        {
            httpListener.Start();
            httpListener.BeginGetContext(ProcContext, null);

        }

        public void Close()
        {
            httpListener.Abort();
            httpListener.Stop();
            this.httpListener.Close();
        }


        private void ProcContext(IAsyncResult ar)
        {
            //继续异步监听
            httpListener.BeginGetContext(ProcContext, null);
            //获得context对象
            var context = httpListener.EndGetContext(ar);
            var request = context.Request;
            var response = context.Response;
            HandleRequest(request, response);

        }
        /// <summary>
        /// 在派生类中实现，处理客户端请求
        /// </summary>
        /// <param name="request"></param>
        /// <param name="response"></param>
        protected abstract void HandleRequest(HttpListenerRequest request, HttpListenerResponse response);

        public void Dispose()
        {
            this.Close();
        }
    }
}
